package com.an.groupecho;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

public class MyIdleStateHandler extends ChannelInboundHandlerAdapter {

	private int idleCount;

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		String eventType = null;
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			switch (event.state()) {
			case READER_IDLE:
				eventType = "读空闲";
				break;
			case ALL_IDLE:
				eventType = "读写空闲";
			case WRITER_IDLE:
				eventType = "写空闲";
			default:
				break;
			}
			idleCount++;
		}
		System.out.println("通道【" + ctx.channel().remoteAddress() + "】发生[" + eventType + "],共发生【" + idleCount
				+ "】次！！当前线程：" + Thread.currentThread().getName());
		// 空闲超过一定次数，即时间，那么关闭连接
		if (idleCount > 5000) {
			System.out.println(
					"通道【" + ctx.channel().remoteAddress() + "】空闲时间过长，关闭连接！！当前线程：" + Thread.currentThread().getName());
			ctx.close();
		}
	}

}
